from pydantic import BaseModel
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from typing import Generic, TypeVar, Any
from pydantic import BaseModel
from typing import TypeVar, Generic
from pydantic import BaseModel
from datetime import datetime

T = TypeVar("T", BaseModel, dict, None)


# class ResultAPISchema(BaseModel):
#     code: int
#     message: str
#     data: object
#     lists: List | None
#     total: int | None


def date_formater(v):
    print("v", v)
    return v.strftime("%Y-%m-%d %H:%M:%S")


class ResultAPI(Generic[T]):
    def __new__(
        cls, code=200, msg="success", data: None | Any = None, show: bool = False
    ):

        res = dict(code=code, msg=msg, data=data, show=show)

        return JSONResponse(
            status_code=200,
            content=jsonable_encoder(
                res,
                by_alias=True,
                custom_encoder={
                    datetime: lambda v: date_formater(v) if v else None,
                },
            ),
            media_type="application/json;charset=utf-8",
        )


# class ResultAPI(Generic[T]):
#     def __new__(
#         cls,
#         code=200,
#         message="success",
#         data: T | List[T] = None,
#         count: None | int = None,
#     ):
#         if data is None:
#             schema_data = ResultAPISchema(
#                 code=code, message=message, data=data)
#         elif isinstance(data, list) and (count is not None and count >= 0):
#             schema_data = ResultAPISchema(
#                 code=code, message=message, data={
#                     "lists": data, "count": count}
#             )
#         else:
#             schema_data = ResultAPISchema(
#                 code=code, message=message, data=data)

#         return JSONResponse(
#             status_code=200,
#             content=jsonable_encoder(schema_data, by_alias=True),
#             media_type="application/json;charset=utf-8",
#         )
